package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageBean;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.entity.YddUserData;
import com.itheima.ydd.service.IYddArticleService;
import com.itheima.ydd.service.IYddUserDataService;
import com.itheima.ydd.service.IYddUserService;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    IYddArticleService iYddArticleService;
    @Autowired
    IYddUserService iYddUserService;
    @Autowired
    IYddUserDataService iYddUserDataService;

    @GetMapping("/myArticle")
    public ResultData myArticle(int page, int limit, HttpSession session){
        //1.构建分页查询对象
        Page<YddArticle> pageInfo = new Page<>(page,limit);
        //2.获取本地线程中的用户id
        Integer userId = (Integer) session.getAttribute("userId");
        //String userId = UserHolder.getUserId();
        //3.构建条件查询器
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        //4.通过用户id查询文章
        queryWrapper.eq(YddArticle::getUserId,userId);
        iYddArticleService.page(pageInfo,queryWrapper);

        PageBean<YddArticle> pageBean = new PageBean<>();
        pageBean.setCurrentPage(pageInfo.getCurrent()); // 当前页
        pageBean.setData(pageInfo.getRecords()); // 封装的具体数据集合
        pageBean.setPageSize(pageInfo.getSize()); // 每页显示条数
        pageBean.setCount(pageInfo.getTotal()); // 总记录数(总条数)
        pageBean.setTotalPages(pageInfo.getPages()); // 总页数
        //5.返回前端数据
        return ResultData.ok("",pageBean);
    }

    @GetMapping("/getUserInfo")
    public ResultData getUserInfo(HttpSession session){
        //1.获取线程中的用户id
        Integer userId = (Integer) session.getAttribute("userId");

        //String userId = UserHolder.getUserId();
        //2.获取用户信息;
        YddUser user = iYddUserService.getById(userId);
        //3.获取文章数;
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getUserId,userId);
        int articleNum = iYddArticleService.count(queryWrapper);
        //4.获取点赞数;
        LambdaQueryWrapper<YddUserData> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(YddUserData::getUserId,userId);
        queryWrapper1.eq(YddUserData::getType,2);
        int zanNum = iYddUserDataService.count(queryWrapper1);
        //5.获取收藏数;
        LambdaQueryWrapper<YddUserData> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(YddUserData::getUserId,userId);
        queryWrapper2.eq(YddUserData::getType,1);
        int collectNum = iYddUserDataService.count(queryWrapper1);
        //6.封装数据
        Map map = new HashMap();
        map.put("userInfo",user);
        map.put("articleNum",articleNum);
        map.put("zanNum",zanNum);
        map.put("collectNum",collectNum);
        return ResultData.ok("",map);
    }

    @PostMapping("/update")
    public ResultData update(@RequestBody YddUser yddUser) {
        iYddUserService.updateById(yddUser);
        return ResultData.ok("修改成功", "");
    }

    /**
     * 获取token中的id
     * @param request
     * @return
     */
    private Integer getUserId(HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        return (Integer) claims.get("id");
    }
    /**
     * 发布文章
     * @param yddArticle
     * @return
     */
    @PostMapping("/addArticle")
    public R save(HttpServletRequest request, @RequestBody YddArticle yddArticle) {

        //获取用户id
        Integer userId = getUserId(request);
        YddUser user = iYddUserService.getById(userId);

        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        long time = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

        yddArticle.setCreateDate(time);
        yddArticle.setUpdateDate(time);
        yddArticle.setUserId(userId);
        yddArticle.setLovenum("0");
        yddArticle.setDefaultData("1");
        yddArticle.setAuthor(user.getUsername());
        iYddArticleService.save(yddArticle);

        R r = new R();
        r.setErrno(0);
        return r;

    }

    /**
     * 查看我的点赞和收藏
     * @param type
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/userDataList")
    public R userDateList(String type, String page, String limit, HttpServletRequest request) {
        log.info("进入查询我的收藏/点赞方法");
        //获取用户id
        Integer userId = getUserId(request);
        log.info(userId.toString());
        //封装分页条件
        Page<YddArticle> pageInfo = new Page<>();
        //判断type的值
        if (type.equals("1")) {
            //如果是1,就代表查询收藏的文章
            LambdaQueryWrapper<YddUserData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YddUserData::getUserId, userId).eq(YddUserData::getType, 1);
            List<YddUserData> list = iYddUserDataService.list(queryWrapper);
            if (list.size() == 0) {
                log.info("没有数据");
                HashMap<String, Object> map;
                map = new HashMap<>();
                map.put("count", pageInfo.getTotal());
                map.put("totalPages", pageInfo.getPages());
                map.put("pageSize", pageInfo.getSize());
                map.put("currentPage", pageInfo.getCurrent());
                map.put("data", pageInfo.getRecords());
                return R.success("list", map);
            }
            ArrayList<Integer> ids = new ArrayList<>();
            for (YddUserData yddUserData : list) {
                ids.add(yddUserData.getArticleId());
            }
            //查询收藏的文章
            LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(YddArticle::getId, ids).orderByDesc(YddArticle::getUpdateDate);
            //分页查询
            iYddArticleService.page(pageInfo, wrapper);
            //返回前端数据
            //将分页数据放在map中
            HashMap<String, Object> map;
            map = new HashMap<>();
            map.put("count", pageInfo.getTotal());
            map.put("totalPages", pageInfo.getPages());
            map.put("pageSize", pageInfo.getSize());
            map.put("currentPage", pageInfo.getCurrent());
            map.put("data", pageInfo.getRecords());
            return R.success("list", map);

        }
        //如果是2代表点赞的文章
        LambdaQueryWrapper<YddUserData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUserData::getUserId, userId).eq(YddUserData::getType, 2);
        List<YddUserData> list = iYddUserDataService.list(queryWrapper);
        if (list.size() == 0) {
            log.info("没有数据");
            HashMap<String, Object> map;
            map = new HashMap<>();
            map.put("count", pageInfo.getTotal());
            map.put("totalPages", pageInfo.getPages());
            map.put("pageSize", pageInfo.getSize());
            map.put("currentPage", pageInfo.getCurrent());
            map.put("data", pageInfo.getRecords());
            return R.success("list", map);

        }
        ArrayList<Integer> ids = new ArrayList<>();
        for (YddUserData yddUserData : list) {
            ids.add(yddUserData.getArticleId());
        }
        //查询收藏的文章
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(YddArticle::getId, ids).orderByDesc(YddArticle::getUpdateDate);
        //分页查询
        iYddArticleService.page(pageInfo, wrapper);
        //返回前端数据
        //将分页数据放在map中
        HashMap<String, Object> map;
        map = new HashMap<>();
        map.put("count", pageInfo.getTotal());
        map.put("totalPages", pageInfo.getPages());
        map.put("pageSize", pageInfo.getSize());
        map.put("currentPage", pageInfo.getCurrent());
        map.put("data", pageInfo.getRecords());
        return R.success("list", map);
    }

    /**
     * 点赞/取消点赞和收藏/取消收藏
     *
     * @param type
     * @param articleId
     * @param action
     * @return
     */
    @GetMapping("/userDataHandle")
    public R userDataHandle(String type, @RequestParam("article_id") String articleId, String action, HttpServletRequest request) {
        log.info("进入点赞/收藏方法");
        log.info("type" + type + "文章id" + "动作" + action);
        //获取用户id
        //判断type
        Integer userId = getUserId(request);
        if (type.equals("1")) {
            //判断操作
            if (action.equals("add")) {
                //如果是收藏
                //先判断是否已经收藏
                LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(YddUserData::getArticleId, articleId).eq(YddUserData::getUserId, userId).eq(YddUserData::getType, 1);
                YddUserData one = iYddUserDataService.getOne(wrapper);
                if (one != null) {
                    throw new BusinessException("您已经收藏啦");
                }

                YddUserData yddUserData = new YddUserData().setUserId(userId).setArticleId(Integer.parseInt(articleId)).setType(1);
                iYddUserDataService.save(yddUserData);
                //更改文章更新时间
                LambdaUpdateWrapper<YddArticle> queryWrapper = new LambdaUpdateWrapper<>();
                queryWrapper.set(YddArticle::getUpdateDate, System.currentTimeMillis());
                queryWrapper.eq(YddArticle::getId, articleId);
                iYddArticleService.update(queryWrapper);
                return R.success("", "");
            }
            //如果是取消收藏
            LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YddUserData::getUserId, userId).eq(YddUserData::getType, 1).eq(YddUserData::getArticleId, articleId);
            iYddUserDataService.remove(wrapper);
            return R.success("", "");
        }

        //判断操作
        if (action.equals("add")) {
            //如果是点赞
            //先判断是否已经点赞
            LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YddUserData::getArticleId, articleId).eq(YddUserData::getUserId, userId).eq(YddUserData::getType, 2);
            YddUserData one = iYddUserDataService.getOne(wrapper);
            if (one != null) {
                throw new BusinessException("您已经点赞啦");
            }


            YddUserData yddUserData = new YddUserData().setUserId(userId).setArticleId(Integer.parseInt(articleId)).setType(2);
            iYddUserDataService.save(yddUserData);
            //更新文章点赞数量
            LambdaUpdateWrapper<YddArticle> queryWrapper = new LambdaUpdateWrapper<>();
            YddArticle article = iYddArticleService.getById(articleId);
            int loveNum = Integer.parseInt(article.getLovenum()) + 1;
            log.info("点赞:{}", Integer.parseInt(article.getLovenum()) + 1);
            queryWrapper.set(YddArticle::getLovenum, loveNum);
            queryWrapper.set(YddArticle::getUpdateDate, System.currentTimeMillis());
            queryWrapper.eq(YddArticle::getId, articleId);
            iYddArticleService.update(queryWrapper);
            return R.success("", "");
        }
        //如果是取消点赞
        LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUserData::getUserId, userId).eq(YddUserData::getType, 2).eq(YddUserData::getArticleId, articleId);
        iYddUserDataService.remove(wrapper);
        return R.success("", "");
    }

    /**
     * 修改文章
     * @param yddArticle
     * @return
     */
    @PostMapping("/editArticle")
    public ResultData updateArticle(@RequestBody YddArticle yddArticle) {
        iYddArticleService.updateById(yddArticle);
        return ResultData.ok("", "修改成功");
    }

    /**
     * 删除文章
     * @param id
     * @return
     */
    @GetMapping("/delArticle")
    public ResultData delArticle(String id) {
        iYddArticleService.removeById(id);
        return ResultData.ok("", "删除成功");
    }
}
